﻿using MKAdmin.DTO.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MKAdmin.ToolKit
{
    public static class IpAddressHelper
    {
        public static Result<string> GetIpAddress()
        {
            var ipResult = new Result<string>();

            string CustomerIP = "";
            try
            {
                if (HttpContext.Current == null
                || HttpContext.Current.Request == null
                || HttpContext.Current.Request.ServerVariables == null)
                {
                    ipResult.data = "";
                    return ipResult;
                }
                
                //CDN加速后取到的IP simone 090805
                CustomerIP = HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    ipResult.data = "";
                    return ipResult;
                }

                CustomerIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (!String.IsNullOrEmpty(CustomerIP))
                {
                    ipResult.data = "";
                    return ipResult;
                }

                if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (CustomerIP == null)
                        CustomerIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    CustomerIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                }

                if (string.Compare(CustomerIP, "unknown", true) == 0)
                {
                    CustomerIP = HttpContext.Current.Request.UserHostAddress;
                }
            }
            catch
            {
                CustomerIP = "";
            }
            ipResult.data = CustomerIP;

            return ipResult;
        }
    }
}
